#include "ffaencoderthread.h"
#include"queue/ffaframequeue.h"
#include"queue/ffapacketqueue.h"
#include"encoder/ffaencoder.h"
#include"muxer/ffmuxer.h"
#include"decoder/ffadecoder.h"

FFAEncoderThread::FFAEncoderThread()
{

}

FFAEncoderThread::~FFAEncoderThread()
{
    if(aPars){
        delete aPars;
        aPars = nullptr;
    }
}

void FFAEncoderThread::init(FFAEncoder *aEncoder_, FFMuxer *muxer_,FFADecoder*aDecoder_, FFAFrameQueue *frmQueue_)
{
    aEncoder = aEncoder_;
    muxer = muxer_;
    aDecoder = aDecoder_;
    frmQueue = frmQueue_;
}

void FFAEncoderThread::run()
{
    int64_t firstFramePts = 0;  // 用于存储第一帧的绝对PTS
    bool firstFrame = true;    // 标记是否为第一帧

    while(!m_stop){
        AVFrame* frame = frmQueue->dequeue();
        if(frame == nullptr){
            m_stop = true;
            break;
        }
        if(aPars == nullptr){
            initEncoder(frame);
        }

        if(firstFrame){
            firstFramePts = frame->pts;  // 记录第一帧的绝对PTS
            firstFrame = false;

            // 第一帧的相对PTS为0
            aEncoder->encode(frame, streamIndex, 0, microphoneTimeBase);
        }
        else{
            // 计算当前帧的相对PTS
            int64_t relativePts = frame->pts - firstFramePts;
            aEncoder->encode(frame, streamIndex, relativePts,  microphoneTimeBase);
        }

        std::cerr << "relativePTS: " << (firstFrame? 0 : frame->pts - firstFramePts) << std::endl;

        av_frame_unref(frame);
        av_frame_free(&frame);
    }
}

void FFAEncoderThread::initEncoder(AVFrame* frame)
{
    aPars = new FFAudioPars();
    FFAudioPars* tmpPars = aDecoder->getAudioPars();
    memcpy(aPars,tmpPars,sizeof(FFAudioPars));
    microphoneTimeBase = aPars->timeBase;

    aEncoder->initAudio(frame);
    muxer->addStream(aEncoder->getCodecCtx());
    streamIndex = muxer->getAStreamIndex();
}
